package admin

import (
	"exercise/application/yiran/app/libs"
	"exercise/application/yiran/app/model"
	"exercise/application/yiran/app/request/adminRequest"
	"fmt"
	"github.com/gin-gonic/gin"
)

type floorService struct {
}

func (*floorService) List(ctx *gin.Context, request *adminRequest.FloorListRequest) (map[string]interface{}, error) {
	schoolId, _ := ctx.Get("schoolId")
	list := make([]model.FloorToJzw, 0)
	paging := model.Paging{}
	paging.Page = request.Page
	paging.PageSize = request.PageSize

	sql := "school_id = ? "
	where := []interface{}{schoolId}

	if request.JzwId != 0 {
		sql += " AND jzw_id = ?"
		where = append(where, request.JzwId)
	}
	total, err := model.NewDb("").FindAllAndCount(&list, sql, where, model.OrderOrGroup{}, paging, []string{"Jzw"})
	if err != nil {
		return nil, fmt.Errorf("暂无数据：%w", err)
	}

	return map[string]interface{}{
		"list":  list,
		"total": total,
	}, err
}

func (*floorService) Add(ctx *gin.Context, request *adminRequest.AddFloorRequest) (id int64, err error) {
	schoolId, _ := ctx.Get("schoolId")

	jzw := new(model.Jzw)
	err = model.NewDb("").FindOne(jzw, "id = ?", []interface{}{request.JzwId}, "*", []string{})
	if jzw == nil {
		return 0, fmt.Errorf("建筑物不存在")
	}

	floor := new(model.Floor)
	floor.FloorName = request.FloorName
	floor.Floor = request.Floor
	floor.SchoolId = schoolId.(int64)
	floor.JzwId = request.JzwId
	floor.JzwName = jzw.JzwName
	floor.CreateTime = libs.CurrentTime()

	err = model.NewDb("").InsertRecord(floor)
	if err != nil {
		return id, err
	}

	return floor.Id, nil
}

func (*floorService) Edit(request *adminRequest.EditFloorRequest) error {
	jzw := new(model.Jzw)
	err := model.NewDb("").FindOne(jzw, "id = ?", []interface{}{request.JzwId}, "*", []string{})
	if err != nil {
		return fmt.Errorf("建筑物不存在")
	}
	floor := new(model.Floor)
	err = model.NewDb("").FindOne(floor, "id = ? ", []interface{}{request.Id}, "*", []string{})
	if err != nil {
		return err
	}
	floor.FloorName = request.FloorName
	floor.Floor = request.Floor
	floor.JzwId = request.JzwId
	floor.JzwName = jzw.JzwName

	err = model.NewDb("").SaveRecord(floor)
	if err != nil {
		return err
	}
	return nil
}

func (*floorService) Detail(ctx *gin.Context) (res interface{}, err error) {
	id := ctx.Param("id")
	floor := new(model.FloorToJzw)
	err = model.NewDb("").FindOne(floor, "id = ? ", []interface{}{id}, "*", []string{"Jzw"})
	if err != nil {
		return nil, fmt.Errorf("数据异常：%w", err)
	}
	return floor, err
}

func (*floorService) Deleted(ctx *gin.Context) error {
	id := ctx.Param("id")
	floor := new(model.Floor)
	err := model.NewDb("").DeleteRecord(floor, "id = ?", []interface{}{id})
	return err
}

func NewFloorService() *floorService {
	return &floorService{}
}
